
import axios from 'axios'
import {getRedirectPath} from '../util'
const ERROR_MSG='ERROR_MSG'
const LOAD_DATA='LOAD_DATA'
const AUTH_SUCCESS = 'AUTH_SUCCESS'
const LOGINOUT='LOGINOUT'
const LOAD_DATA_END='LOAD_DATA_END'
const initState={
    redirectTo:'',
    msg:'',
    user:'',
    type:'',
    loadDataEnd:false
}
export function user(state=initState,action) {
    switch (action.type) {
        case AUTH_SUCCESS:
            return {...state, msg:'',redirectTo:getRedirectPath(action.payload),...action.payload}
        
        case ERROR_MSG:
            return {...state,msg:action.msg,isAuth:false};
       
        case LOAD_DATA:
            return {...state,...action.payload}

        case LOGINOUT:
        console.log('caoasdsd')
            return {...initState,redirectTo:'/login',user:''}
        case LOAD_DATA_END:
            return{...state,loadDataEnd:true}
        default:
            return state;
    }
    
}
export function loadData(data) {
    const data2=Object.assign({},data,{loadDataEnd:true})
    return {type:LOAD_DATA,payload:data2}
}
export function errMsg(msg) {
    return {msg,type:ERROR_MSG}
}
export function logoutSubmit(params) {
    return dispatch=>{
        dispatch({type:LOGINOUT,})
    }
    // return {type:LOGINOUT}
}
export function loadDataEnd(){
    return {type:LOAD_DATA_END}
}

function authSuccess(obj){
	const {pwd,...data} = obj
	return {type: AUTH_SUCCESS, payload:data}
}
export function update(data) {
    return dispatch=>{
        axios.post('/user/update',data)
        .then(res=>{
            if(res.status==200&&res.data.code==0){
                dispatch(authSuccess(res.data.data))
            }else{
                dispatch(errMsg(res.data.msg))
            }
        })
    }
}
export function  login({user,pwd}) {
    if(!user||!pwd){
        return errMsg('用户名密码必须输入')
    }
    return async dispatch=>{
        let res =await axios.post('/user/login',{user,pwd})
        // .then(res=>{
            if(res.status==200){
                
                switch (Number(res.data.code)) {
                    case 0:dispatch(authSuccess(res.data.data))
                        break;
                    case 1:dispatch(errMsg(res.data.msg))
                        break;
                    default:dispatch(errMsg('未知错误'))
                }
            }else{
                dispatch(errMsg('操作失败 服务器正忙'))
            }
        // })
    }
}
export function registerMethods({user,pwd,repeatpwd,type}) {
    
    if(!user||!pwd||!type){
        return errMsg('用户名密码必须输入')
    }
    if(pwd!==repeatpwd){
        return errMsg('密码不一致')
    }
    return dispatch=>{
        axios.post('/user/register',{user,pwd,type})
        .then(res=>{
            if(res.status==200&&res.data.code==0){
                dispatch(authSuccess({user,pwd,type}))
            }else{
                dispatch(errMsg(res.data.msg))
            }
        })
    }
}
